<script setup>
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores';
import { userLoginService } from '@/api/user';

const router = useRouter();
const userStore = useUserStore();

// 表单数据
const formModel = ref({
  userName: '',
  password: ''
});

// 表单校验规则
const rules = {
  userName: [
    { required: true, message: '请输入学工号', trigger: 'onBlur' },
    { pattern: /^[A-Z]\d{8}$/, message: '学工号格式不正确', trigger: 'onBlur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'onBlur' },
    { min: 6, message: '密码长度至少6位', trigger: 'onBlur' }
  ]
};
onMounted(() => {
  showToast('欢迎使用毕设系统');
});


// 登录处理
const login = async () => {
  console.log(formModel.value);
  const res = await userLoginService(formModel.value); // 调用登录接口
  userStore.setToken(res.data); // 存储 token
  userStore.getUser()// 获取用户信息一次
  showSuccessToast('登录成功');


  // 同时支持 backUrl 和 redirect 参数，Vue 3 版本
  const redirect = router.currentRoute.value.query.backUrl
    || router.currentRoute.value.query.redirect
    || '/';
  // 使用 setTimeout 延迟跳转，这里设置的是 2000 毫秒（即 2 秒）
  setTimeout(() => {
    router.replace(redirect);
  }, 1000);

};
</script>

<template>
  <div class="login-container">
    <van-nav-bar title="用户登录" left-arrow @click-left="router.go(-1)" />

    <div class="cover">
    </div>

    <van-form @submit="login" class="login-form">
      <van-cell-group inset>
        <!-- 学工号输入 -->
        <van-field v-model="formModel.userName" 
        name="userName" label="学工号" 
        placeholder="请输入学工号" :rules="rules.userName"
          clearable />

        <!-- 密码输入 -->
        <van-field v-model="formModel.password" name="password" label="密码" placeholder="请输入密码" :rules="rules.password"
          type="password" clearable />
      </van-cell-group>

      <div style="margin: 32px 16px 10px;">
        <van-button round block type="primary" native-type="submit" :loading="userStore.loading" loading-text="登录中...">
          立即登录
        </van-button>
      </div>
    </van-form>

    <div class="extra-actions">
      <a>&nbsp;&nbsp;忘记密码?</a>
    </div>
  </div>
</template>

<style lang="less" scoped>
.login-container {
  min-height: 100vh;
  // background: #f5f5f5;
  background: linear-gradient(to bottom, #87CEEB, #E0F6FF); /* 天蓝色渐变背景 */
}
.cover {
  height: 242px;
  background-image: url('../../assets/logo_2.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
.login-form {
  margin-top: 10px;
  position: relative;
  z-index: 1; /* 确保表单在渐变背景上方 */
}

.extra-actions {
  text-align: center;
  // margin-top: 20px;
  color: #1989fa;
  font-size: 14px;

  a {
    cursor: pointer;

    &:hover {
      opacity: 0.8;
    }
  }
}
</style>